import * as vscode from "vscode";
import { spawn, exec } from "child_process";
import { tmpdir } from "os";
import * as fs from "fs";
import * as path from "path";
import axios from "axios";
import * as packages from "../../package.json";
import http from "./http";

let pkg = packages as any;

function insertToEnd(text: string, type?: number): Promise<boolean> {
  if (type === undefined) {
    type = insertType.cursor;
  }
  return new Promise((resolve, reject) => {
    const editor = vscode.window.activeTextEditor;
    if (editor) {
      editor
        .edit((editBuilder) => {
          switch (type) {
            case insertType.start:
              editBuilder.insert(new vscode.Position(0, 0), text);
              break;
            case insertType.end:
              let linenumber =
                vscode.window.activeTextEditor?.document.lineCount || 1;
              let pos =
                vscode.window.activeTextEditor?.document.lineAt(linenumber - 1)
                  .range.end || new vscode.Position(0, 0);
              editBuilder.insert(pos, text);
              break;
            case insertType.cursor:
              editBuilder.insert(editor.selection.active, text);
              break;
            default:
              break;
          }
        })
        .then(resolve);
    }
  });
}
// eslint-disable-next-line @typescript-eslint/naming-convention
enum insertType {
  start = 1,
  end = 2,
  cursor = 3,
}

// 执行 ps1文件
function execps1() {
  const scriptPath = path.join(
    __dirname,
    "..",
    "..",
    "imgtogitee/asserts/SaveClipboardImg.ps1"
  );

  let command =
    "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe";
  let powershellExisted = fs.existsSync(command);

  if (!powershellExisted) {
    command = "powershell";
  }

  const powershell = spawn(command, [
    "-noprofile",
    "-noninteractive",
    "-nologo",
    "-sta",
    "-executionpolicy",
    "unrestricted",
    "-windowstyle",
    "hidden",
    "-file",
    scriptPath,
  ]);
  // the powershell can't auto exit in windows 7 .
  let timer = setTimeout(() => powershell.kill(), 2000);

  // powershell.on('error', (e: any) => {
  //     if (e.code === 'ENOENT') {
  //         vscode.window.showErrorMessage('zjk_Windows');
  //     } else {
  //         vscode.window.showErrorMessage(e);
  //     }
  // });
  powershell.on("exit", function (code, signal) {
    // console.debug('exit', code, signal);
  });
  powershell.stdout.on("data", (data) => {
    clearTimeout(timer);
    timer = setTimeout(() => powershell.kill(), 2000);
  });
  powershell.on("close", (code) => {
    // resolve(output.trim().split('\n').map(i => i.trim()));
  });
}
function getTmpFolder() {
  let savePath = path.join(tmpdir(), pkg.name);
  if (!fs.existsSync(savePath)) {
    fs.mkdirSync(savePath);
  }
  return savePath;
}
function getPasteImage(imagePath: string): Promise<string[]> {
  return new Promise((resolve, reject) => {
    if (!imagePath) {
      return;
    }

    let platform = process.platform;
    if (platform === "win32") {
      // Windows
      const scriptPath = path.join(__dirname, "..", "asserts/pc.ps1");
      // vscode.window.showErrorMessage(scriptPath);
      let command =
        "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe";
      let powershellExisted = fs.existsSync(command);
      let output = "";
      if (!powershellExisted) {
        command = "powershell";
      }

      const powershell = spawn(command, [
        "-noprofile",
        "-noninteractive",
        "-nologo",
        "-sta",
        "-executionpolicy",
        "unrestricted",
        "-windowstyle",
        "hidden",
        "-file",
        scriptPath,
        imagePath,
      ]);
      // the powershell can't auto exit in windows 7 .
      let timer = setTimeout(() => powershell.kill(), 2000);

      powershell.on("error", (e: any) => {
        if (e.code === "ENOENT") {
          vscode.window.showErrorMessage(e);
        } else {
          vscode.window.showErrorMessage(e);
        }
      });

      powershell.on("exit", function (code, signal) {
        console.debug("exit", code, signal);
      });
      powershell.stdout.on("data", (data) => {
        data
          .toString()
          .split("\n")
          .forEach(
            (d: string | string[]) =>
              (output += d.indexOf("Active code page:") < 0 ? d + "\n" : "")
          );
        clearTimeout(timer);
        timer = setTimeout(() => powershell.kill(), 2000);
      });
      powershell.on("close", (code) => {
        resolve(
          output
            .trim()
            .split("\n")
            .map((i) => i.trim())
        );
      });
    }
  });
}
// https://gitee.com/api/v5/repos/kudsu/BlogImgs/contents/imgs/001.png
// eslint-disable-next-line @typescript-eslint/naming-convention
async function uploadgitee(url: string, access_token: string, content: string) {
  // await 后面也可以跟的是Promise实例对象
  let ret = http.post(url, {
    // eslint-disable-next-line @typescript-eslint/naming-convention
    access_token: access_token,
    content: content,
    message: "vscode upload",
  });

  return ret;
}

function imgtobase64(url: string) {
  return new Promise((resolve, reject) => {
    fs.readFile(url, "binary", function (err, data) {
      if (err) {
        console.log(err);
      } else {
        const buffer = new Buffer(data, "binary");
        // baseURL = 'data: image/png;base64,' + buffer.toString('base64');
        // return buffer.toString('base64');
        resolve(buffer.toString("base64"));
      }
    });
  });
}

function getemo() {
  var emoarr = [
    "🐵",
    "🐒",
    "🦍",
    "🦧",
    "🐕",
    "🦮",
    "🐕‍🦺",
    "🐩",
    "🐺",
    "🦊",
    "🦝",
    "🐱",
    "🐈",
    "🦁",
    "🐯",
    "🐅",
    "🐆",
    "🦄",
    "🦓",
    "🦌",
    "🐂",
    "🐃",
    "🐄",
    "🐷",
    "🐖",
    "🐗",
    "🐽",
    "🐏",
    "🐑",
    "🐐",
    "🐪",
    "🐫",
    "🦙",
    "🦒",
    "🐘",
    "🦏",
    "🦛",
    "🐭",
    "🐁",
    "🐀",
    "🐹",
    "🐰",
    "🐇",
    "🍇",
    "🍈",
    "🍉",
    "🍊",
    "🍋",
    "🍌",
    "🍍",
    "🥭",
    "🍎",
    "🍏",
    "🍑",
    "🍒",
    "🍓",
    "🥝",
    "🍅",
    "🥥",
    "🥑",
    "🍆",
    "🥔",
    "🥕",
    "🌽",
    "🥒",
    "🥬",
    "🥦",
    "🧄",
    "🧅",
    "🍄",
    "🥜",
    "🌰",
    "🍞",
    "🥐",
    "🥖",
    "🥨",
    "🥯",
    "🥞",
    "🧇",
    "🧀",
    "🍖",
    "🍗",
    "🥩",
    "🥓",
    "🍔",
    "🍟",
    "🍕",
    "🌭",
    "🥪",
    "🌮",
    "🌯",
    "🥙",
    "🧆",
    "🥚",
    "🍳",
    "🥘",
    "🍲",
    "🥣",
    "🥗",
    "🍿",
    "🧈",
    "🧂",
    "🥫",
    "🍱",
    "🍘",
    "🍙",
    "🍚",
    "🍛",
    "🍜",
    "🍝",
    "🍠",
    "🍢",
    "🍣",
    "🍤",
    "🍥",
    "🥮",
    "🍡",
    "🥟",
    "🥠",
    "🥡",
    "🦀",
    "🦞",
    "🦐",
    "🦑",
    "🦪",
    "🍦",
    "🍧",
    "🍨",
    "🍩",
    "🍪",
    "🎂",
    "🍰",
    "🧁",
    "🥧",
    "🍫",
    "🍬",
    "🍭",
    "🍮",
    "🍯",
    "🍼",
    "🥛",
    "☕",
    "🍵",
    "🍶",
    "🍾",
    "🍷",
    "🍸",
    "🍹",
    "🎃",
    "🎄",
    "🎆",
    "🎇",
    "🧨",
    "✨",
    "🎈",
    "🎉",
    "🎊",
    "🎋",
    "🎍",
    "🎎",
    "🎏",
    "🎐",
    "🎑",
    "🧧",
    "🎀",
    "🎁",
    "🎫",
    "🥂",
    "🥃",
    "🥤",
    "🧃",
    "🧉",
    "🧊",
    "🏆",
    "🏅",
    "🥇",
    "🥈",
    "🥉",
    "⚾",
    "🥎",
    "🏐",
    "🏈",
    "🏉",
    "🎾",
    "🥏",
    "🎳",
    "🏏",
    "🏑",
    "🏒",
    "🥍",
    "🏓",
    "🏸",
    "🥊",
    "🥋",
    "🥅",
    "⛳",
    "⛸",
    "🎣",
    "🤿",
    "🎽",
    "🎿",
    "🛷",
    "🥌",
    "🦔",
    "🦇",
    "🌱",
    "🌲",
    "🌳",
    "🌴",
    "🌵",
    "🌾",
    "🌿",
    "🍀",
    "🍁",
    "🍂",
    "🍃",
    "🐨",
    "🐼",
    "🦥",
    "🦦",
    "🦨",
    "🦘",
    "🦡",
    "🐾",
    "🐊",
    "🦎",
    "🐍",
    "🐲",
    "🐉",
    "🦕",
    "🦖",
    "🐸",
    "🐳",
    "🐋",
    "🐬",
    "🐟",
    "🐡",
    "🦈",
    "🐙",
    "🐚",
    "🐌",
    "🦋",
    "🐜",
    "🐝",
    "💐",
    "🌸",
    "💮",
    "🌹",
    "🥀",
    "🌺",
    "🌻",
    "🌼",
    "🌷",
    "🐞",
    "🦗",
    "🦂",
    "🦟",
    "🦠",
  ];

  return emoarr[Math.floor(Math.random() * emoarr.length)];
}

export default {
  insertToEnd,
  insertType,
  execps1,
  getPasteImage,
  getTmpFolder,
  uploadgitee,
  imgtobase64,
  pkg,
  getemo,
};
